import re
import django_filters

from connection.models import Connection


class ConnectionFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(method='get_name_filter')
    state = django_filters.CharFilter(method='get_state_filter')
    type = django_filters.CharFilter(method='get_type_filter')

    class Meta:
        model = Connection
        fields = ('name', 'state', 'partner', 'thirdparty_app', 'thirdparty_id')

    def get_name_filter(self, queryset, name, value):
        if value:
            queryset = queryset.filter(partner__name__icontains=value)
        return queryset

    def get_state_filter(self, queryset, name, value):
        if value:
            value_list = re.sub(r'[;；,，]', ' ', value).split()
            queryset = queryset.filter(state__in=value_list)
        return queryset

    def get_type_filter(self, queryset, name, value):
        if value:
            queryset = queryset.filter(partner__type=value)
        return queryset
